<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-left">
        <div class="welcome-left">
          <h2>欢迎使用样品需求填写系统</h2>
        </div>
        <div class="illustration">
          <img src="../assets/login-illustration.png" alt="登录插图" />
        </div>
      </div>
      <div class="login-right">
        <div class="login-header">
          <img src="../assets/logo.png" alt="系统Logo" class="logo" />
          <h2>用户登录</h2>
        </div>

        <form @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <div class="input-with-icon">
              <i class="iconfont icon-fa-user"></i>
              <input
                  type="text"
                  id="username"
                  v-model="loginForm.username"
                  placeholder="请输入用户名"
                  required
                  autocomplete="username"
              />
            </div>
          </div>
          <div class="form-group">
            <div class="input-with-icon">
              <i class="iconfont icon-fa-lock"></i>
              <input
                  :type="showPassword ? 'text' : 'password'"
                  id="password"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  required
                  autocomplete="current-password"
              />
              <i
                  :class="['iconfont', showPassword ? 'icon-fa-eye-slash' : 'icon-fa-eye', 'toggle-password']"
                  @click="showPassword = !showPassword"
              ></i>
            </div>
          </div>
          <div class="form-options">
            <label class="remember-me">
              <input type="checkbox" v-model="loginForm.rememberMe" />
              <span>记住我</span>
            </label>
          </div>
          <button type="submit" class="login-button" :disabled="loading">
            <span v-if="!loading">登录</span>
            <span v-else class="loading-spinner"></span>
          </button>
        </form>

        <div v-if="errorMessage" class="error-message">
          <i class="iconfont icon-fa-exclamation-circle"></i>
          {{ errorMessage }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { mapMutations } from 'vuex';

export default {
  name: 'Login',
  data() {
    return {
      showPassword: false,
      loading: false,
      errorMessage: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false
      }
    };
  },
  created() {
    const rememberedUsername = localStorage.getItem('rememberedUsername');
    if (rememberedUsername) {
      this.loginForm.username = rememberedUsername;
      this.loginForm.rememberMe = true;
    }
  },
  methods: {
    ...mapMutations(['setUser', 'setToken']),

    async handleLogin() {
      if (!this.loginForm.username || !this.loginForm.password) {
        this.errorMessage = '请输入用户名和密码';
        return;
      }

      this.loading = true;
      this.errorMessage = '';

      try {
        const response = await axios.post('/api/auth/login', {
          username: this.loginForm.username,
          password: this.loginForm.password
        });

        if (response.data && response.data.data && response.data.data.token) {
          const token = response.data.data.token;

          this.setToken(token);
          localStorage.setItem('token', token);

          if (this.loginForm.rememberMe) {
            localStorage.setItem('rememberedUsername', this.loginForm.username);
          } else {
            localStorage.removeItem('rememberedUsername');
          }

          await this.fetchUserInfo(token);

          this.$router.push('/projects');
        } else {
          this.errorMessage = '登录失败，请检查用户名和密码';
        }
      } catch (error) {
        console.error('登录错误:', error);
        this.handleLoginError(error);
      } finally {
        this.loading = false;
      }
    },

    async fetchUserInfo(token) {
      try {
        const response = await axios.get('/api/auth/current', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        alert(JSON.stringify(response.data.data, null, 2));
        if (response.data && response.data.data) {
          this.setUser(response.data.data);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    handleLoginError(error) {
      if (error.response) {
        switch (error.response.status) {
          case 401:
            this.errorMessage = '用户名或密码错误';
            break;
          case 500:
            this.errorMessage = '服务器错误，请稍后再试';
            break;
          default:
            this.errorMessage = `登录失败 (${error.response.status})`;
        }
      } else if (error.request) {
        this.errorMessage = '网络错误，请检查您的连接';
      } else {
        this.errorMessage = '登录过程中发生错误';
      }
    }
  }
};
</script>

<style scoped>
@import url('/icon/font_4948858_9v5hgrg1lv/iconfont.css');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  padding: 65px;
}

.login-background {
  display: flex;
  width: 100%;
  max-width: 800px;
  background: white;
  border-radius: 20px; /* 整体容器圆边 */
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 480px;
}

.login-left {
  flex: 1;
  background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  color: white;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-radius: 20px 0 0 20px; /* 左边主体框圆边 */
}

.illustration {
  text-align: center;
  margin: 40px 0;
}

.illustration img {
  max-width: 100%;
  height: auto;
}

.login-right {
  flex: 1;
  padding: 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
  border-radius: 0 20px 20px 0; /* 右边卡片圆边 */
}

.login-header {
  margin-bottom: 30px;
  text-align: center;
}

.login-header .logo {
  height: 80px;
}

.login-header h2 {
  font-size: 24px;
  margin-bottom: 8px;
  font-weight: 600;
  background: linear-gradient(45deg, #6a11cb, #2575fc); /* 设置背景渐变 */
  -webkit-background-clip: text; /* 裁剪背景到文本区域 */
  -webkit-text-fill-color: transparent; /* 使文本颜色透明，显示背景 */
}

.login-header p {
  font-size: 14px;
  color: #777;
}

.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #555;
  font-weight: 500;
}

.input-with-icon {
  position: relative;
}

.input-with-icon i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.input-with-icon .toggle-password {
  left: auto;
  right: 15px;
  cursor: pointer;
  color: #666;
}

.input-with-icon input {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 1px solid #ddd;
  border-radius: 8px; /* 输入框圆边 */
  font-size: 14px;
  transition: all 0.3s;
}

.input-with-icon input:focus {
  border-color: #6a11cb;
  box-shadow: 0 0 0 3px rgba(106, 17, 203, 0.1);
  outline: none;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 13px;
}

.remember-me {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #555;
}

.remember-me input {
  margin-right: 8px;
}

.login-button {
  width: 100%;
  padding: 14px;
  background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  color: white;
  border: none;
  border-radius: 8px; /* 登录按钮圆边 */
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
}

.login-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.loading-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  margin-top: 15px;
  padding: 10px 15px;
  background: #ffebee;
  color: #c62828;
  border-radius: 6px; /* 错误信息圆边 */
  font-size: 14px;
  display: flex;
  align-items: center;
}

.error-message i {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .login-background {
    flex-direction: column;
    height: auto;
  }

  .login-left {
    padding: 30px;
    border-radius: 20px 20px 0 0; /* 响应式调整圆边 */
  }

  .login-right {
    padding: 30px;
    border-radius: 0 0 20px 20px; /* 响应式调整圆边 */
  }
}
</style>